<template>
  <c-dialog ref="dialog" width="70vw" :open-fun="openFun" title="发起异常" @open="openHandle" @close="closeHandle">
    <c-list ref="form" :model="formData" :rules="formRules" label-width="140px">
      <c-list-item label="软装陈列任务号" :value="detail.softwearTaskCode" :span="0.5" />
      <c-list-item label="门店建设项目号" :value="detail.constCode" :span="0.5" />
      <c-list-item label="所属门店" :value="detail.shopName" />
      <c-list-item prop="exceptionHandleId" label="异常类型">
        <el-select v-model="formData.exceptionHandleId" placeholder="异常类型" clearable>
          <el-option v-for="(e,i) in exceptionList" :key="i" :label="e.exceptionType" :value="e.id" />
        </el-select>
      </c-list-item>
      <c-list-item prop="customerManagerCode" label="客户经理">
        <c-single-dialog
          ref="customerManagerCode"
          v-model="formData.customerManagerCode"
          :label.sync="formData.customerManagerName"
          :props="{label:'name',value:'adAccount'}"
          :disabled="account.length===0"
          :focus-query="true"
          :config="{
            title:'客户经理',
            width:'600px',
            interfacePath: '/slm-admin/api/v1/user/listCustomerManagerByAccounts',
            method:'post',
            paramField:'',
            filtersRaw:filtersRaw,
            paramsRaw:{},
            setting:[
              {prop:'adAccount',title:'编码',width:100},
              {prop:'name',title:'名称',width:100},
              {prop:'tel',title:'电话',width:200}
            ]
          }"
        />
      </c-list-item>
    </c-list>
    <c-section title="软装过程异常附件">
      <c-file-list v-model="files" view-type="image" type-code="ACCESS024" />
    </c-section>
    <c-section title="异常明细">
      <c-table-box hide-func checkbox :table-config="tableConfig" :data="tableData" table-height="400" @selection-change="selectionChange">
        <div slot="btn">
          <c-button type="primary" @click="addTableRow">新增</c-button>
          <c-button type="primary" @click="removeTableRow">删除</c-button>
        </div>
      </c-table-box>
    </c-section>
    <div class="btn-container">
      <c-button @click="cancelHandle">取消</c-button>
      <c-button type="primary" @click="confirmHandle">提交</c-button>
    </div>
  </c-dialog>
</template>
<script>
import { getCustomerCode, postAccountPage } from '@/api/check'
import { postShopException, postExceptionType } from '@/api/decorate'
import { otherFiltersItem } from '@/utils'
export default {
  name: 'Abnormal',
  components: {
  },
  props: {
    selData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      exceptionList: [],
      account: [],
      formData: {
        exceptionHandleId: '',
        customerManagerCode: '',
        customerManagerName: ''
      },
      formRules: {
        exceptionHandleId: [{ required: true, message: '请选择异常类型', trigger: 'change' }]
      },
      tableConfig: {
        interfacePath: '',
        setting: [
          {
            prop: 'problemCategory',
            label: '异常问题类型',
            render: (h, row) => {
              return h('c-dict-select', {
                props: {
                  dictTypeCode: 'PROBLEM_CATEGORY',
                  clearable: true,
                  value: row.problemCategory
                },
                on: {
                  change: v => {
                    this.$set(row, 'problemCategory', v)
                    this.$set(row, 'stockoutType', '')
                  }
                }
              })
            }
          },
          // 异常问题类型选择【公司缺货】时，缺货类别可编辑。异常问题类型选择非【公司缺货】时，缺货类别不可编辑
          {
            prop: 'stockoutType',
            label: '缺货类别',
            render: (h, row) => {
              return h('c-dict-select', {
                props: {
                  dictTypeCode: 'STOCKOUT_TYPE',
                  clearable: true,
                  disabled: row.problemCategory !== 'A',
                  value: row.stockoutType
                },
                on: {
                  change: v => {
                    this.$set(row, 'stockoutType', v)
                  }
                }
              })
            }
          },
          {
            prop: 'exceptionDesc',
            label: '异常问题描述/缺货型号、订单号',
            edit: {
              canEdit: true,
              editType: 'text',
              maxlength: 2000
            }
          },
          {
            prop: 'solution',
            label: '异常解决方案',
            edit: {
              canEdit: true,
              editType: 'text',
              maxlength: 2000
            }
          },
          {
            prop: 'remark',
            label: '备注',
            edit: {
              canEdit: true,
              editType: 'text',
              maxlength: 2000
            }
          }
        ]
      },
      tableData: [],
      selections: [],
      files: []
    }
  },
  computed: {
    detail() {
      return this.selData.length > 0 ? this.selData[0] : {}
    },
    filtersRaw() {
      return [otherFiltersItem('accounts', `${this.account.join(',')}`, 'in')] // 没有错，不加[]
    }
  },
  methods: {
    async getCustomerCode() {
      let customerCode = ''
      if (this.selData[0].clientCode) {
        customerCode = this.selData[0].clientCode
      } else {
        await getCustomerCode(this.selData[0].shopCode).then(code => {
          customerCode = code
        })
      }
      return await postAccountPage(customerCode).then(res => {
        this.account = res.data.records.map(e => e.code)
        if (!this.account || this.account.length === 0) this.$message.warning('业务账号未配置')
      })
    },
    openFun() {
      if (!this.singleJudge(this.selData, '发起异常', true)) {
        return false
      }
      const d = this.selData[0]
      // 只有门店建设项目号状态“正常”，
      // 软装陈列数据步骤发起异常2022/6/27修改
      if (d.constState !== 'A') {
        this.$message.warning('门店建设项目号状态为正常时才能发起异常！')
        return false
      } else if (!['A1', 'B1', 'C1', 'D1', 'D2', 'E1', 'E2'].includes(d.steps)) {
        this.$message.warning('当前步骤不能发起异常！')
        return false
      }
      this.getCustomerCode()
      this.formData.customerManagerCode = this.detail.applicantCode
      this.formData.customerManagerName = this.detail.applicantName
      return true
    },
    openHandle() {
      const data = new FormData()
      data.append('pageFlag', false)
      data.append('filtersRaw', JSON.stringify([
        // otherFiltersItem('belongModel', 'SHOP_SOFTWEAR_DISPLAY', '='),
        otherFiltersItem('typeCode', '[EXCEPT021,EXCEPT022,EXCEPT023]', 'in')
      ]))
      postExceptionType(data).then(res => {
        this.exceptionList = res.data.records
      })
    },
    selectionChange(v) {
      this.selections = v
    },
    addTableRow() {
      this.tableData.unshift({
        problemCategory: '',
        stockoutType: '',
        exceptionDesc: '',
        solution: '',
        remark: ''
      })
    },
    removeTableRow() {
      if (this.selections.length <= 0) {
        this.$message.warning('请选择数据！')
        return
      }
      this.$msgbox({
        type: 'warning',
        title: '删除',
        message: '确认删除？'
      }).then(() => {
        this.tableData = this.tableData.filter(e => {
          return !this.selections.includes(e)
        })
        this.selections = []
      })
    },
    // 验证异常明细
    validateAbnormal() {
      if (this.tableData.length === 0) {
        this.$message.warning('请填写异常明细数据！')
        return Promise.reject('')
      }
      for (const row of this.tableData) {
        const { problemCategory, stockoutType, exceptionDesc } = row
        // TODO: 1.当软装问题明细中，异常问题类型为“公司缺货”时，“缺货类别”必填；
        if (problemCategory === 'A' && stockoutType === '') {
          this.$message.warning('异常问题类型为“公司缺货”时，“缺货类别”必填！')
          return Promise.reject()
        }
        // TODO: 2.异常问题描述字段必填；异常解决方案、备注选填；
        if (exceptionDesc === '') {
          this.$message.warning('请输入异常问题描述！')
          return Promise.reject()
        }
      }
      return Promise.resolve()
    },
    confirmHandle() {
      return Promise.all([this.$refs.form.validate(), this.validateAbnormal()]).then(() => {
        // console.log(this.formData, this.tableData, this.files)
        const d = this.detail
        const data = {
          modelId: d.id,
          constCode: d.constCode,
          bizCode: d.decorationTaskCode,
          exceptionHandleId: this.formData.exceptionHandleId,
          customerManagerCode: this.formData.customerManagerCode,
          customerManagerName: this.formData.customerManagerName,
          shopExceptionDetailDTOS: this.tableData,
          shopAttachmentDTOS: this.$getFiles(this.files, this.detail.id)
        }
        return postShopException(data).then(res => {
          this.$message.success('操作成功！')
          this.$emit('on-success')
          this.$refs.dialog.visible = false
        })
      })
    },
    cancelHandle() {
      this.$refs.dialog.visible = false
    },
    closeHandle() {
      this.tableData = []
      this.selections = []
      this.files = []
    }
  }
}
</script>
